import "reflect-metadata";
import * as express from "express";
import * as expressJwt from 'express-jwt'
import { createConnection } from "typeorm";
import { Server } from 'socket.io'
import { JWT_SECRET, logString, port, socketPort } from './utils/constants'
import { catchError }  from './middlewares/binMiddlewares'
import socketServer from "./socket";
import useRoter from './routers'
import useMiddleware from './middlewares'

createConnection().then(async connection => {
  // 创建实例
  const app = express();

  // app.disable('etag'); // 关闭缓存
  // 开启 socket 监听
  const io = new Server(socketPort, { cors: { origin: '*' }})
  socketServer(io)

  // *挂载中间件
  useMiddleware(app)
  // 设置静态图片访问的路径
  app.use('/public/', express.static('./public/'))
  // 在路由之前，配置解析 Token 的中间件
  app.use(expressJwt({ secret: JWT_SECRET, algorithms: ['HS256'] }).unless({ path: [/^\/api\/v1\/(admin|teacher|student)\/allow\//] }))
  // *挂载路由
  useRoter(app) 
  app.use(catchError) // 定义错误的中间件，必须放在路由中间件后面
  
  // 开启服务
  app.listen(port, () => {
    console.log('\x1B[36m%s\x1B[0m', logString);
  });

}).catch(error => console.log(error));